package org.baitu.zzim.decoder;
import io.netty.channel.ChannelHandler.Sharable;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.baitu.zzim.model.ChatMessage;
import org.baitu.zzim.pojo.chat.ChatMessageOuterClass;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.List;

@Component
@Sharable
public class MessageEncoder extends MessageToMessageEncoder<ChatMessage> {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void encode(ChannelHandlerContext ctx, ChatMessage message, List<Object> out) throws Exception {
        String json = objectMapper.writeValueAsString(message);
        ByteBuf buffer = Unpooled.copiedBuffer(json, StandardCharsets.UTF_8);
        out.add(new TextWebSocketFrame(buffer));
    }
}